package com.taotao.search.dao;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.solr.client.solrj.SolrQuery;
import org.apache.solr.client.solrj.SolrServer;
import org.apache.solr.client.solrj.response.QueryResponse;
import org.apache.solr.common.SolrDocument;
import org.apache.solr.common.SolrDocumentList;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import com.taotao.search.pojo.SearchItem;
import com.taotao.search.pojo.SearchResult;
/**
 * Search工程的dao层(访问solr服务器索引库数据)
* <p>Title:SearchDaoImpl</p>
* <p>Description:</p> 
* @author JSJ
* @date 2017年10月8日下午8:35:25
 */
@Repository
public class SearchDaoImpl implements SearchDao {

	@Autowired
	private SolrServer solrServer;
    /**
     * 根据查询条件SolrQuery对象进行结果查询
     */
	@Override
	public SearchResult search(SolrQuery query) throws Exception {
		QueryResponse response = solrServer.query(query);
		// 取商品查询结果集
		SolrDocumentList results = response.getResults();
		// 取高亮item_title结果集
		Map<String, Map<String, List<String>>> highlighting = response
				.getHighlighting();
		// 创建封装商品信息的集合
		List<SearchItem> itemList = new ArrayList<>();
		for (SolrDocument document : results) {
			SearchItem item = new SearchItem();
			item.setId((String) document.get("id"));
			item.setSell_point((String) document.get("item_sell_point"));
			item.setPrice((Long) document.get("item_price"));
			item.setImage((String) document.get("item_image"));
			item.setCategory_name((String) document.get("item_category_name"));
			// 取item_title页面高亮显示
			List<String> list = highlighting.get(document.get("id")).get(
					"item_title");
			String itemTitle = "";
			// 判断item_title是否存在高亮字段
			if (list != null && list.size() > 0) {
				itemTitle = list.get(0);
				item.setTitle(itemTitle);
			} else {
				itemTitle = (String) document.get("item_title");
			}
			// 添加item
			itemList.add(item);
		}
		// 创建搜索结果对象并且封装结果
		SearchResult result = new SearchResult();
		result.setItemList(itemList);
		result.setRecordCount(results.getNumFound());
		return result;
	}

}
